package com.example.controller;

import cn.hutool.core.date.DateUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class FileController {
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String comPartyId = (String) request.getAttribute("comPartyId");
        String yearMonth = DateUtil.format(new Date(), "yyyyMM");

        // 将文件保存到 nginx 的静态资源目录
        String basePath = "D:/nginx-1.23.3/html/vm/dist/upload/";
        String uploadDir = basePath + comPartyId + "/" + yearMonth + "/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        // 生成文件名
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = System.currentTimeMillis() + suffix;

        File dest = new File(uploadDir + fileName);
        file.transferTo(dest);

        // 构建返回URL
        String imageUrl = request.getScheme() + "://" + "192.168.119.201:9000/upload/" + comPartyId + "/" + yearMonth + "/" + fileName;

        Map<String, Object> result = new HashMap<>();
        result.put("url", imageUrl);
        return result;
    }

    @PostMapping("/uploadPolicy")
    public Map<String, Object> uploadPolicy(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String comPartyId = (String) request.getAttribute("comPartyId");
        String yearMonth = DateUtil.format(new Date(), "yyyyMM");

        // 将文件保存到 nginx 的静态资源目录
        String basePath = "D:/nginx-1.23.3/html/vm/dist/uploadPolicy/";
        String uploadDir = basePath + comPartyId + "/" + yearMonth + "/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        // 生成文件名
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = System.currentTimeMillis() + suffix;

        File dest = new File(uploadDir + fileName);
        file.transferTo(dest);

        // 构建返回URL
        String imageUrl = request.getScheme() + "://" + "192.168.119.201:9000/uploadPolicy/" + comPartyId + "/" + yearMonth + "/" + fileName;

        Map<String, Object> result = new HashMap<>();
        result.put("url", imageUrl);
        return result;
    }


}
